package com.netcracker.studportal.server.facade;

import java.util.Map;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.log4j.Logger;
import org.json.simple.JSONObject;

import com.netcracker.studportal.server.model.User;
import com.netcracker.studportal.server.util.FacadeUtil;
import com.netcracker.studportal.server.util.FactoryDAO;

public class FacadeGuest {
	private static final Logger LOG = Logger.getLogger(FacadeGuest.class);
	
	/**
	 * Method for getting list of materials for exam.
	 * 
	 * @param param
	 *  JSONObject in format:
	 *  "login" 	: "value"
	 *  "password" 	: "value"
	 * 
	 * @return 
	 * 	JSONObject in format:
	 *  "user_id" 		: "value",
	 *  "login" 		: "value",
	 *  "type" 			: "value",
	 *  "material_file" : "value",
	 *  if user is student
	 *  	"stud_first_name" : "value",
	 *  	"stud_last_name"  : "value",
	 *  if user is professor
	 *  	"prof_first_name" 	: "value",
	 *  	"patronymic" 		: "value",
	 *  	"prof_last_name"	: "value";
	 *  
	 * 
	 * In case of errors:
	 * 	JSONObject in format:
	 *  "error" 		: "error_message",
	 *  "stacktrace" 	: "error_stacktrace";
	 */
	public String authorization(String param) throws Exception {
		if (LOG.isDebugEnabled()) {
			LOG.debug("Method 'authorization' called with parameters = " + param);
		}
		
		try {
			Map<String, String> inputParams = 
					FacadeUtil.extractInputParams(param, new String[]{"login", "password"});
			String login = inputParams.get("login");
			String password = inputParams.get("password");
			
			User user = FactoryDAO.getUsersDAO().getUserByLoginPass(login, password);
			
			if (user == null) {
				return null;
			}
			
			String result = user.kJSON().toJSONString();
				
			return result;
		} catch (Exception e) {
			LOG.error("Error: ", e);
			JSONObject obj = new JSONObject();
			obj.put("error", e.getMessage());
			obj.put("stacktrace", ExceptionUtils.getFullStackTrace(e));
			
			return obj.toString();
		}	
	}
}
